﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Player : MonoBehaviour
{

    CharacterController2D cc;
    Animator anim;
    Rigidbody2D rigid;

    Transform stampPoint;
    public GameObject prefabDeadAnim;


    float move;
    bool jump;

    public float speed = 5f;
    // Start is called before the first frame update
    void Start()
    {
        cc = GetComponent<CharacterController2D>();
        anim = GetComponent<Animator>();
        rigid = GetComponent<Rigidbody2D>();

        stampPoint = transform.Find("StampPoint");
    }

    // Update is called once per frame
    void Update()
    {
        move = Input.GetAxis("Horizontal");
        float temp = move;
        
        move *= speed;
        jump = Input.GetButton("Jump");

        // 动画部分
        if (cc.isGrounded) {
            anim.SetFloat("speed", Math.Abs(temp));
            anim.SetBool("jump_up", false);
            anim.SetBool("jump_down", false);
        } else {
            Vector2 vel = rigid.velocity;
            if (vel.y > 0) {
                anim.SetBool("jump_up", true);
                anim.SetBool("jump_down", false);
            } else {
                anim.SetBool("jump_up", false);
                anim.SetBool("jump_down", true);
            }
        }
    }

    void FixedUpdate() {
        StampTest();

        cc.Move(move,jump);
    }
    private void StampTest() {
        Collider2D c = Physics2D.OverlapCircle(stampPoint.position, 0.1f, LayerMask.GetMask("Enemy"));
        if (c == null) {
            return;
        }
        // 踩到了怪物
        Debug.Log("踩到怪物"+c.name);
        Destroy(c.gameObject);

        GameObject da = Instantiate(prefabDeadAnim, null);
        da.transform.position = c.transform.position;

        rigid.velocity = new Vector2(rigid.velocity.x, 0);
        rigid.AddForce(new Vector2(0, 200));
    }

    private void OnCollisionEnter2D(Collision2D collision) {
        if (collision.gameObject.layer != LayerMask.NameToLayer("Enemy")) {
            return;
        }
        Debug.Log("玩家死亡");

        Invoke("Restart", 2); // 延迟2秒执行
    }

    void Restart() {
        // 加载第一个场景
        SceneManager.LoadScene(0);
    }
}
